package com.easymin.weixin;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 工具类
 * 
 * @author 秦波 createTime 2018-11-8
 *
 */
@Component
public class CommUtil {

    /**
     * 时间戳判断
     * 
     * @param time
     *            UTC毫秒时间戳
     * @return true 超时
     */
    public static boolean isTime(Long time) {
        Long times = System.currentTimeMillis();
        times = Long.valueOf(times) - Long.valueOf(time);
        if (times.toString().indexOf("-") == -1) {
            if (times >= 600000) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 签名判断
     * 
     * @param time
     *            UTC毫秒时间戳
     * @param nonce_str
     *            随机字符串
     * @param sign
     *            签名
     * @return true 签名错误
     */
    public static boolean isSign(Long time, String nonce_str, String sign) {
        // 醉无忧专属 appkey
        String appkey = "92bd6eeeabe549c7a2932a6528af8bff";
        String signs = appkey + "&" + time + "&" + nonce_str;
        signs = SHA256(signs);
        if (!signs.equals(sign)) {
            return true;
        }
        return false;
    }
    
//    public static void main(String[] args) {
//        String appkey = "92bd6eeeabe549c7a2932a6528af8bff";
//        String signs = appkey + "&" +  1544685411000L + "&" + "154e6989da41";
//        signs = SHA256(signs);
//        System.out.println(signs);
//    }
   
    /**
     * 传入文本内容，返回 SHA-256 串
     * 
     * @param strText
     * @return
     */
    public static String SHA256(final String strText) {
        return SHA(strText, "SHA-256");
    }

    /**
     * 传入文本内容，返回 SHA-512 串
     * 
     * @param strText
     * @return
     */
    public static String SHA512(final String strText) {
        return SHA(strText, "SHA-512");
    }

    /**
     * 字符串 SHA 加密
     * 
     * @param strSourceText
     * @return
     */
    private static String SHA(final String strText, final String strType) {
        // 返回值
        String strResult = null;
        // 是否是有效字符串
        if (strText != null && strText.length() > 0) {
            try {
                // SHA 加密开始
                // 创建加密对象 并傳入加密类型
                MessageDigest messageDigest = MessageDigest.getInstance(strType);
                // 传入要加密的字符串
                messageDigest.update(strText.getBytes());
                // 得到 byte 类型结果
                byte byteBuffer[] = messageDigest.digest();
                // 將 byte 转换为 string
                StringBuffer strHexString = new StringBuffer();
                // 遍历 byte buffer
                for (int i = 0; i < byteBuffer.length; i++) {
                    String hex = Integer.toHexString(0xff & byteBuffer[i]);
                    if (hex.length() == 1) {
                        strHexString.append('0');
                    }
                    strHexString.append(hex);
                }
                // 得到返回結果
                strResult = strHexString.toString();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return strResult;
    }

    /**
     * 生成随机字符串
     * 
     * @param length
     *            长度
     * @return
     */
    public static String getRandomString(int length) {
        StringBuffer sb = new StringBuffer();
        String string = "abcdefghijklmnopqrstuvwxyzQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        int len = string.length();
        for (int i = 0; i < length; i++) {
            sb.append(string.charAt(getRandom(len - 1)));
        }
        return sb.toString();
    }


    private static int getRandom(int count) {
        return (int) Math.round(Math.random() * (count));
    }

    /**
     * xml转Map
     * @param req HttpServletRequest请求
     */
    public static Map<String,String> xmlToMap(HttpServletRequest req) throws IOException, DocumentException {

        Map<String,String> map = new HashMap<String, String>();

        InputStream is = req.getInputStream();

        SAXReader reader = new SAXReader();

        Document doc = reader.read(is);

        Element root = doc.getRootElement();

        List<Element> elements = root.elements();

        for(Element e:elements){

            map.put(e.getName(), e.getText());

        }

        is.close();

        return map;

    }
}
